/*
 * Copyright (c) 2009 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.stripesbook.rayures.service.impl;

import java.util.ArrayList;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import org.stripesbook.rayures.service.LookupStrategy;
import org.stripesbook.rayures.util.Location;

public class LookupStrategyImpl implements LookupStrategy {

  public List<Location> getSearchLocations(ActionBean actionBean, String eventName) {
    List<Location> locations = new ArrayList<Location>();
    addLocations(locations, actionBean.getClass(), eventName);
    return locations;
  }

  private void addLocations(List<Location> locations, Class<?> actionBeanClass, String eventName) {
    // Start with action bean class name + event name
    if (eventName.length() > 0) {
      addTo(locations, new Location(actionBeanClass.getName() + "_" + eventName));
    }

    // Add the action bean class name
    addTo(locations, new Location(actionBeanClass.getName()));

    // Go up action bean class package hierarchy
    for (String pkg = actionBeanClass.getPackage().getName(); pkg.length() > 0;
         pkg = getParentPackage(pkg))
    {
      addTo(locations, new Location(pkg, ""));
    }

    // Recursively add locations up the action bean class hierarchy
    for (Class<?> cls = actionBeanClass.getSuperclass(); !cls.equals(Object.class);
         cls = cls.getSuperclass())
    {
      addLocations(locations, cls, "");
    }
  }

  private void addTo(List<Location> list, Location location) {
    if (!list.contains(location)) {
      list.add(location);
    }
  }

  private String getParentPackage(String packageName) {
    int index = packageName.lastIndexOf(".");

    if (index != -1) {
      return packageName.substring(0, index);
    }
    return "";
  }
}
